from model import Demand, sql_session
from form import ApplyForm, StuQueryForm, LoginForm, InspectForm, HistoryForm
from config import service_logger
import config

import time, datetime

from sqlalchemy import and_
from sqlalchemy.orm.exc import NoResultFound


def handle_apply(request):
    # stu_name, stu_id, stu_phone, parent_phone, start_time, stop_time, reason, location
    form = ApplyForm(request)
    response = {}
    if not form.validate():
        service_logger.info("student apply fail, invalid form")
        response['result'] = 'ERROR_INVALID_FORM'
        return response
    data = form.data
    data['state'] = 0
    data['apply_time'] = datetime.datetime.now()
    demand = Demand(**data)
    sql_session.add(demand)
    sql_session.commit()

    service_logger.info("student:%s, id:%s, apply for leave success" % (data['stu_name'], data['stu_id']))
    response['result'] = 'ok'
    return response


def handle_query(request):
    # stu_name, stu_id
    form = StuQueryForm(request)
    response = {}
    if not form.validate():
        service_logger.info("student query fail, invalid form")
        response['result'] = 'ERROR_INVALID_FORM'
        return response
    stu_name = form.stu_name.data
    stu_id = form.stu_id.data

    demands = sql_session.query(Demand).filter(and_(Demand.stu_id == stu_id, Demand.stu_name == stu_name)).all()
    if demands is None or len(demands) == 0:
        service_logger.info("student query fail, user not found")
        response['result'] = 'ERROR_USER_NOT_FOUND'
        return response
    demand_list = []
    for demand in demands:
        data = {
            'demand_id': demand.demand_id,
            'start_time': demand.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'stop_time': demand.stop_time.strftime('%Y-%m-%d %H:%M:%S'),
            'state': demand.state,
            'reason': demand.reason,
            'location': demand.location,
            'director_comment': demand.director_comment,
            'school_comment': demand.school_comment,
        }
        demand_list.append(data)

    service_logger.info("student:%s, id:%s, query success" % (stu_name, stu_id))

    response['result'] = 'ok'
    response['list'] = demand_list
    response['uid'] = stu_id
    return response


def handle_query_detail(request, session=None):
    response = {}
    auth = session.get('auth')
    if auth is None or auth != 'stu':
        response['result'] = 'ERROR_PERMISSION_DENIED'
        return response
    demand_id = request['query_id']
    demands = sql_session.query(Demand).filter(Demand.demand_id == demand_id).all()
    if demands is None or len(demands) == 0:
        response['result'] = 'ERROR_DEMAND_NOT_FOUND'
        return response
    demand = demands[0]

    if demand.stu_id != session['uid']:
        response['result'] = 'ERROR_PERMISSION_DENIED'
        return response

    response = {
        'result': 'ok',
        'start_time': demand.start_time.strftime('%Y-%m-%d %H:%M:%S'),
        'stop_time': demand.stop_time.strftime('%Y-%m-%d %H:%M:%S'),
        'state': demand.state,
        'reason': demand.reason,
        'location': demand.location,
        'director_comment': demand.director_comment,
        'school_comment': demand.school_comment,
    }
    return response


def handle_admin_login(request):
    form = LoginForm(request)
    response = {}
    if not form.validate():
        service_logger.info("admin login fail, invalid form")
        response['result'] = 'ERROR_INVALID_FORM'
        return response
    username = form.username.data
    password = form.password.data
    if username == config.ADMIN_NAME and password == config.ADMIN_PASSWD:
        service_logger.info("admin login success")
        return {'result': 'ok'}
    else:
        service_logger.info("admin login fail, permission denied")
        return {'result': 'ERROR_PERMISSION_DENIED'}


def handle_admin_list(request, session=None):
    response = {}
    auth = session.get('auth')
    if auth is None or auth != 'admin':
        service_logger.info("admin query list fail, permission denied")
        response['result'] = 'ERROR_PERMISSION_DENIED'
        return response
    demands = sql_session.query(Demand).filter(Demand.state == 0).all()
    demand_list = []
    for demand in demands:
        data = {
            'demand_id': demand.demand_id,
            'stu_name': demand.stu_name,
            'stu_id': demand.stu_id,
            'stu_phone': demand.stu_phone,
            'parent_phone': demand.parent_phone,
            'start_time': demand.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'stop_time': demand.stop_time.strftime('%Y-%m-%d %H:%M:%S'),
            'reason': demand.reason,
            'location': demand.location,
            'state': demand.state
        }
        demand_list.append(data)

    service_logger.info("admin query request list success")
    response['result'] = 'ok'
    response['list'] = demand_list
    return response


def handle_admin_inspect(request, session=None):
    response = {}

    auth = session.get('auth')
    if auth is None or auth != 'admin':
        service_logger.info("admin inspect fail, permission denied")
        response['result'] = 'ERROR_PERMISSION_DENIED'
        return response

    form = InspectForm(request)
    response = {}
    if not form.validate():
        service_logger.info("admin inspect fail, invalid form")
        response['result'] = 'ERROR_INVALID_FORM'
        return response

    data = form.data
    demand_id = data['demand_id']
    demands = sql_session.query(Demand).filter(Demand.demand_id == demand_id).all()
    if demands is None or len(demands) == 0:
        service_logger.info("admin inspect fail, demand not found")
        response['result'] = 'ERROR_DEMAND_NOT_FOUND'
        return response
    demand = demands[0]

    demand.state = data['state']
    demand.director_comment = data.get('director_comment', '')
    demand.school_comment = data.get('school_comment', '')
    sql_session.add(demand)
    sql_session.commit()

    service_logger.info("admin inspect demand:%s success, state:%s" % (demand_id, demand.state))
    response = {'result': 'ok'}
    return response


def handle_admin_history(request, session=None):
    response = {}

    auth = session.get('auth')
    if auth is None or auth != 'admin':
        service_logger.info("admin query history fail, permission denied")
        response['result'] = 'ERROR_PERMISSION_DENIED'
        return response

    form = HistoryForm(request)
    response = {}
    if not form.validate():
        service_logger.info("admin query history fail, invalid form")
        response['result'] = 'ERROR_INVALID_FORM'
        return response

    data = form.data
    if data.get('start_time'):
        start = data['start_time']
    else:
        start = datetime.datetime(2017, 1, 1, 0, 0)
    if data.get('stop_time'):
        stop = data['stop_time']
    else:
        stop = datetime.datetime(2030, 1, 1, 23, 59)
    if data.get('limit'):
        limit = data['limit']
    else:
        limit = 65535

    demands = sql_session.query(Demand).filter(and_(Demand.start_time > start, Demand.stop_time < stop))\
        .limit(limit).all()

    demand_list = []
    for demand in demands:
        data = {
            'demand_id': demand.demand_id,
            'stu_name': demand.stu_name,
            'stu_id': demand.stu_id,
            'stu_phone': demand.stu_phone,
            'parent_phone': demand.parent_phone,
            'start_time': demand.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'stop_time': demand.stop_time.strftime('%Y-%m-%d %H:%M:%S'),
            'reason': demand.reason,
            'location': demand.location,
            'state': demand.state
        }
        demand_list.append(data)

    service_logger.info("admin query history success")
    response['result'] = 'ok'
    response['list'] = demand_list
    return response
